<?php

namespace app\admin\controller;


use app\common\exception\ApiException;

class Category extends BaseController {
    public function add() {
        if (request()->isPost()) {
            $data = input('post.');
            try {
                $id = model('Category')->add($data);
            } catch (\Exception $e) {
                throw new ApiException($e->getMessage(), 400, 1);
            }
            if ($id) {
                return show(0, '上传成功');
            } else {
                return show(1, '上传失败');
            }
        }
    }

    public function getCategoryList() {
        $result = model('Category')->getCategoryList();
        return show(0, 'ok', $result);
    }

    public function saveCategory() {
        if (request()->post()) {
            $data = input('post.');
            if (empty($data['categoryId'])) {
                $data['parent_id'] = 0;
                $maxOrderNum       = model('Category')->getMaxOrderNum();
                $data['listorder'] = $maxOrderNum + 1;
            } else {
                $data['parent_id'] = $data['categoryId'];
            }
            if (!empty($data['id'])) {
                $id = model('Category')->edit($data, $data['id']);

            } else {
                $id = model('Category')->add($data);
            }
            if ($id) {
                return show(config('code.success'), 'add category success', ['id' => $id]);
            }
        }
    }

    public function getList() {
        $data = input('get.');
        if ($data['type'] === 'main') {
            $condition['parent_id'] = [
                'eq', 0
            ];
        } elseif ($data['type'] === 'sec') {
            $condition['parent_id'] = [
                'eq', $data['id']
            ];
        } elseif ($data['type'] === 'all') {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $result = model('Category')->getList($condition);
        return show(config('code.success'), 'get category success', $result);
    }

    public function changeStatus() {
        if (request()->isPost()) {
            $id     = input('post.id');
            $status = input('post.status');
            $result = model('Category')->changeStatus($id, $status);
            if (!$result) {
                return show(1, 'change status failed');
            }
            return show(0, 'change status success');
        }
    }

    public function deleteCategory() {
        if (request()->isPost()) {
            $id = input('post.id');
            model('Category')->deleteCategory($id);
            return show(0, 'delete status success');
        }
    }

    public function changeListOrder() {
        if (request()->isPost()) {
            $data = input('post.');
            model('Category')->changeListOrder($data);
            return show(0, 'change order success');
        }
    }

}